package com.haruhi.controller;

import com.haruhi.entity.FileDetail;
import com.haruhi.entity.vo.ResponseEntity;
import com.haruhi.service.FileDetailService;
import com.haruhi.utils.ParamUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.List;

@RestController
public class DownloadController {

    private static final Logger LOG = LoggerFactory.getLogger(DownloadController.class);

    @Value("${fileConfig.charset}")
    private String utf8;

    @Value("${fileConfig.filePath}")
    private String filePath;

//    @Autowired
//    private FileDetailService fileDetailService;

    @PostMapping(value = "/download")
    public void download(HttpServletResponse response, HttpServletRequest request, @RequestBody FileDetail detail){
        response.setCharacterEncoding(utf8);
        String name = detail.getUuid()+"."+detail.getType();
        File file = new File(filePath + name);
        BufferedInputStream bis = null;
        BufferedOutputStream bos = null;
        try {
            response.setContentType("application/x-download");
//            response.setContentType("application/octet-stream");
            response.setContentLengthLong(file.length());
            response.setHeader("Content-Disposition", "attachment;filename="+ URLEncoder.encode(detail.getName(),utf8));
//            response.setHeader("Accept-Range","bytes");
            bis = new BufferedInputStream(new FileInputStream(file));
            bos = new BufferedOutputStream(response.getOutputStream());
            byte[] buff = new byte[1024 * 1024 * 3];
            int len;
            while ((len = bis.read(buff)) != -1){
                bos.write(buff,0,len);
            }
        }catch (IOException e){
            LOG.error("下载控制器,输出流写入中==>{}",e.getMessage());
            e.printStackTrace();
        }finally {
            if(null != bis){
                try {
                    bis.close();
                } catch (IOException e) {
                    LOG.error("下载控制器,关闭输入流中==>{}",e.getMessage());
//                    e.printStackTrace();
                }
            }
            if(null != bos){
                try {
                    bos.close();
                } catch (IOException e) {
                    LOG.error("下载控制器,关闭输入流中==>{}",e.getMessage());
//                    e.printStackTrace();
                }
            }
        }

    }

    @GetMapping("/download")
    public void download(HttpServletResponse response, HttpServletRequest request,@RequestParam String uuid,@RequestParam String type,@RequestParam Integer id,@RequestParam String name,@RequestParam String uploader ){

        FileDetail detail = new FileDetail();
        detail.setUploader(uploader);
        detail.setUuid(uuid);
        detail.setName(name);
        detail.setId(id);
        detail.setType(type);
        download(response,request,detail );
    }

    /**
     * 这个请求用来检查参数,以及文件是否存在服务器
     * 防止两次文件写入操作
     * @param detail
     * @return
     */
    @PostMapping("/download/check")
    public ResponseEntity check(@RequestBody FileDetail detail){
        if(null == detail || ParamUtil.isEmpty(detail.getUuid()) || ParamUtil.isEmpty(detail.getName())){
            return ResponseEntity.fail(-2,"参数错误");
        }
        String name = detail.getUuid()+"."+detail.getType();
        File file = new File(filePath+name);
        if(!file.exists() || !file.isFile()){
            return ResponseEntity.fail(-3,"资源不存在!");
        }
        return ResponseEntity.success(0,"OK");
    }

}
